package com.mzj.saas;

import com.mzj.saas.filter.AuthFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.io.File;

@EnableAsync
@EnableScheduling
@SpringBootApplication(scanBasePackages = {"com.mzj", "com.haixiaoke"})
@MapperScan(value = "com.haixiaoke.saas.repository.mapper")
public class  AppletServiceApplication {
    private static final Logger log = LoggerFactory.getLogger(AppletServiceApplication.class);
    @Value("${server.tomcat.basedir}")
    private String tomcatBasedir;
    @Value("${spring.application.name}")
    private String applicationName;

    public static void main(String[] args) {
        try {
            new SpringApplicationBuilder(AppletServiceApplication.class).run(args);
            log.info("                                                 \n" +
                    "(♥◠‿◠)ﾉﾞ  启动成功   ლ(´ڡ`ლ)ﾞ                     \n" +
                    "   _____ __  ______________________________       \n" +
                    "  / ___// / / / ____/ ____/ ____/ ___/ ___/       \n" +
                    "  \\__ \\/ / / / /   / /   / __/  \\__ \\\\__ \\  \n" +
                    " ___/ / /_/ / /___/ /___/ /___ ___/ /__/ /        \n" +
                    "/____/\\____/\\____/\\____/_____//____/____/      \n");
        } catch (Exception e) {
            System.err.println("c" + e.getMessage());
        }
    }

    /**
     * 支持跨域访问
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(configSource);
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }


    //初始化tomcat上传图片目录
    @Bean
    public String initTomcatUploadDir() {
        String dir = tomcatBasedir + "work/Tomcat/localhost/" + applicationName;
        File targetFile = new File(dir);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        return dir;
    }
}
